package com.android.flickrapitest;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.content.Intent;

import java.util.List;


public class FlickrApiTestActivity extends Activity {

    private static final String TAG = "Gallery1";

    static final String ACTION = "com.android.gallery1.MAIN";

    static final String EXTRA_NSID = "com.android.gallery1.extra_nsid";
    static final String EXTRA_USER = "com.android.gallery1.extra_user";
    
    static final String TEST_USER = "lphpc";

    private static final int PHOTOS_COUNT_PER_PAGE = 6;


    private Flickr.User mUser;
    private String mUsername;


    private Flickr.PhotoList mPhotoList;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        // Try to find a user name in the saved instance state or the intent
        // that launched the activity. If no valid user NSID can be found, we
        // just close the activity.
        if (!initialize(savedInstanceState)) {
            finish();
            return;
        }
        loadPhotos ();

        if (mPhotoList != null)
            Log.d (TAG, "Succeed to get photos.");
        else
            Log.d (TAG, "Failed to get photos.");


        //setContentView(R.layout.main);        
        setContentView(R.layout.main); //setContentView(R.layout.gallery_1);
        
        // Reference the Gallery view
        Gallery g = (Gallery) findViewById(R.id.gallery);
        // Set the adapter to our custom adapter (below)
        g.setAdapter(new ImageAdapter(this));

        // Set a item click listener, and just Toast the clicked position
        g.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                Toast.makeText(FlickrApiTestActivity.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });

        // We also want to show context menu for longpressed items in the gallery
        registerForContextMenu(g);        
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	menu.setHeaderTitle("Menu Header");
        menu.add(R.string.gallery_2_text);
        menu.add(R.string.gallery_2_text);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        Toast.makeText(this, "Longpress: " + info.position, Toast.LENGTH_SHORT).show();
        return true;
    }

    public class ImageAdapter extends BaseAdapter {
        int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            mContext = c;
            // See res/values/attrs.xml for the <declare-styleable> that defines
            // Gallery1.
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            mGalleryItemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);
/*
            i.setImageResource(mImageIds[position]);
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(136, 88));

            // The preferred Gallery item background
            i.setBackgroundResource(mGalleryItemBackground);
*/
            i.setScaleType(ImageView.ScaleType.FIT_XY);
            i.setLayoutParams(new Gallery.LayoutParams(100, 100));
            Bitmap bmp = getFlickrImage ();
            if (bmp != null)
                i.setImageBitmap (getFlickrImage());
            return i;
        }

        public Bitmap getImage ()
        {
            /* dirName = /sdcard */
            String dirName = Environment.getExternalStorageDirectory().toString();
            String path = dirName + "/";
            path = path + "alexander_larsson.jpg";
            Log.d(TAG, "path = " + path);

            Bitmap b = BitmapFactory.decodeFile(path); 

            return b;
        } 

        public Bitmap getFlickrImage ()
        {

            Flickr.Photo photo = mPhotoList.get(0);
            Bitmap b = photo.loadPhotoBitmap (Flickr.PhotoSize.THUMBNAIL);

            return b;
        } 




        private Context mContext;
        
        private Integer[] mImageIds = {
                R.drawable.gallery_photo_1,
                R.drawable.gallery_photo_2,
                R.drawable.gallery_photo_3,
                R.drawable.gallery_photo_4,
                R.drawable.gallery_photo_5,
                R.drawable.gallery_photo_6,
                R.drawable.gallery_photo_7,
                R.drawable.gallery_photo_8
        };
    }


    /**
     * Starts the PhotostreamActivity for the specified user.
     *
     * @param context The application's environment.
     * @param user The user whose photos to display with MainActivity.
     */
    static void show(Context context, Flickr.User user) {
        final Intent intent = new Intent(ACTION);
        intent.putExtra(EXTRA_USER, user);
        context.startActivity(intent);
    }



    /**
     * Restores a previously saved state or, if missing, finds the user's NSID
     * from the intent used to start the activity.
     *
     * @param savedInstanceState The saved state, if any.
     *
     * @return true if a {@link com.google.android.photostream.Flickr.User} was
     *         found either in the saved state or the intent.
     */
    private boolean initialize(Bundle savedInstanceState) {
/*
        Flickr.User user = Flickr.User.fromId("13964766@N00");
        mUser = user;
*/

        mUser = Flickr.get().findByUserName(TEST_USER);

        if (mUser != null)
            Log.d (TAG, "user id = " + mUser.getId());
        else 
            Log.d (TAG, "user = null.");


        return mUser != null || mUsername != null;
    }


    /**
     * Creates a {@link com.google.android.photostream.Flickr.User} instance
     * from the intent used to start this activity.
     *
     * @return The user whose photos will be displayed, or null if no
     *         user was found.
     */
    private Flickr.User getUser() {
       

        Flickr.User user = Flickr.User.fromId("45701389%40N00");

        return user;
    }


    public Flickr.PhotoList getPhotoList() {

        return Flickr.get().getPublicPhotos(mUser, PHOTOS_COUNT_PER_PAGE, 1);
    }



    private void loadPhotos() {
        mPhotoList = getPhotoList ();
    }


    /**
     * A LoadedPhoto contains the Flickr photo and the Bitmap loaded for that photo.
     */
    private static class LoadedPhoto {
        Bitmap mBitmap;
        Flickr.Photo mPhoto;

        LoadedPhoto(Bitmap bitmap, Flickr.Photo photo) {
            mBitmap = bitmap;
            mPhoto = photo;
        }
    }

    
    
}
